//index.js
//获取应用实例
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');

var goodsDetailsUrl = "goodsApi/goodsInfoYcd";
var goodsShelvesUrl = "goodsApi/shelvesNumberYcd";
var goodsAddcartUrl = "cartApi/apiCartCrudYcd";
var cartUrl = 'cartApi/cartCrudYcd';
var queryAddressUrl = "addressApi/queryAddress";
var orderVerifyUrl = "userOrderApi/orderVerify";
var goodsId;
var goodsSellId;
var skuid;
var that = this;

Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "选择：",
    selectSizePrice: 0,
    shopNum: 1,
    hideShopPopup: true,
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,
    properties: {},
    propertyChildIds: "", 
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar",//购物类型，加入购物车或立即购买，默认为加入购物车
    goodsList:[]
  },

  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  onLoad: function (e) {
    wx.showLoading();
    if (e.inviter_id) {
      wx.setStorage({
        key: 'inviter_id_' + e.id,
        data: e.inviter_id
      })
    };

   // console.log(e);
    goodsId = e.id;
    goodsSellId = e.goodssellid;
    var that = this;
    // 获取购物车数据
    wx.request({
      url: app.globalData.requestUrl + cartUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        type: "2",
        userId: app.globalData.userId,
        signType: 'MD5'
      },

      success: function (res) {
        //将获取到的json数据，
        //console.log(res);//打印日志

        var lists = res.data.data;
        for (var i = 0; i < lists.length; i++) {
          var goodlists = lists[i].cartDetail

        }

        that.setData({
          shopNum: goodlists.length,
        });

      }
    })


    wx.request({
      url: app.globalData.requestUrl + goodsDetailsUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {//这里写你要请求的参数
        goodsID: goodsId,
        userId: app.globalData.userId,
        sign:'000000005febdc50015ffc9ef319003b',
        signType: 'MD5'
      },

      success: function (res) {
        //将获取到的json数据，
       // console.log(res.data);//打印日志
        wx.hideLoading();
        var selectSizeTemp = "";
        if (res.data.list.features) {
          for (var i = 0; i < res.data.list.features.length; i++) {
            selectSizeTemp = selectSizeTemp + " " + res.data.list.features[i].tzlname;
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: res.data.list.cost,
          });
        }


        that.setData({
          //设置数据到控件显示出来
          selectSizePrice: res.data.list.cost,
          buyNumMax: res.data.list.num,
          buyNumber: (res.data.list.num > 0) ? 1 : 0,
          goodsDetail:res.data.list,
          gocarImg: res.data.list.photo[0].path,
          properties: res.data.list.features,
        });

      }
    });

  },
  goShopCar: function () {
    wx.reLaunch({
      url: "/pages/shop-cart/shop-cart"
    });
  },
  toAddShopCar: function () {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  tobuy: function () {
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
    
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function () {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },
  numJianTap: function (e) {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function (e) {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  /**
   * 选择商品规格
   */
  labelItemTap: function (e) {
    var that = this;
   // console.log(e)
    // 取消该分类下的子栏目所有的选中状态
    var childs = that.data.properties[e.currentTarget.dataset.propertyindex].tzzMap;
    for (var i = 0; i < childs.length; i++) {
      that.data.properties[e.currentTarget.dataset.propertyindex].tzzMap[i].active = false;
    }
    // 设置当前选中状态
    that.data.properties[e.currentTarget.dataset.propertyindex].tzzMap[e.currentTarget.dataset.propertychildindex].active = true;
    // 获取所有的选中规格尺寸数据
    var needSelectNum = that.data.properties.length;
    var curSelectNum = 0;
    var propertyChildIds = "";
    var propertyChildNames = "";
    for (var i = 0; i < that.data.properties.length; i++) {
      childs = that.data.properties[i].tzzMap;
      for (var j = 0; j < childs.length; j++) {
        if (childs[j].active) {
          curSelectNum++;
          propertyChildIds = propertyChildIds + that.data.properties[i].tzlid + ":" + childs[j].tzzid + ",";
          propertyChildNames = propertyChildNames + that.data.properties[i].tzlname + ":" + childs[j].tzzname + "  ";
        }
      }
    }

    var canSubmit = false;
    if (needSelectNum == curSelectNum) {
      canSubmit = true;
    }
    //计算当前价格
    if (canSubmit) {
      wx.request({
        url: app.globalData.requestUrl + goodsShelvesUrl,
        method: 'POST',
        data: {//这里写你要请求的参数
          goodsId: goodsId,
          sign: '3c007daeb06aaa0263fcffeab59a7c7a',
          signType: 'MD5'
        },
        success: function (res) {

          that.setData({
            selectSizePrice: res.data.cost,
            propertyChildIds: propertyChildIds,
            propertyChildNames: propertyChildNames,
            buyNumMax: res.data.shelvesNum,
            buyNumber: (res.data.shelvesNum > 0) ? 1 : 0,
            skuid : res.data.skuID
          });
        }
      })
    }
    
    that.setData({
      properties: that.data.properties,
      canSubmit: canSubmit
    })

  },
  /**
  * 加入购物车
  */
  
  addShopCar: function (e) {

    var that = this;
    var num = that.data.buyNumber;
    var skuid = that.data.skuid;
    if (that.data.properties && !that.data.canSubmit) {
      if (!that.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      that.bindGuiGeTap();
      return;
    }
    if (that.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }

    wx.request({
      url: app.globalData.requestUrl + goodsAddcartUrl,
      method: 'POST',
      data: {//这里写你要请求的参数
        goodsSellId: goodsSellId,
        skuId: skuid,
        num: num,
        userId: app.globalData.userId,
        deviceType: "C142001",
        type: "1",
        signType: 'MD5',
      },
      success: function (res) {
        //console.log(res)
        that.setData({

        });
      }
    })

    that.closePopupTap();
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 2000
    })
  
  },
	/**
	  * 立即购买
	  */
  buyNow: function (e) {
    var that = this;
    var num = that.data.buyNumber;
    var skuid = that.data.skuid;
    if (that.data.properties && !that.data.canSubmit) {
      if (!that.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      that.bindGuiGeTap();
      wx.showModal({
        title: '提示',
        content: '请先选择规格尺寸哦~',
        showCancel: false
      })
      return;
    }
    if (that.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }

    that.closePopupTap();
    //console.log(that.data)
    var goodsList = [
      {
        skuId: that.data.skuid,
        goodsSellId: goodsSellId,
        num: that.data.buyNumber,
        cartDetailId: "",
      }
    ];
    wx.navigateTo({
      url: '/pages/to-pay-order/to-pay-order?goodsList=' + JSON.stringify(goodsList) 
    })
  },

  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.basicInfo.name,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.basicInfo.id + '&inviter_id=' + app.globalData.uid,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  reputation: function (goodsId) {
    var that = this;
    wx.request({
      url: '' + app.globalData.subDomain + '/shop/goods/reputation',
      data: {
        goodsId: goodsId
      },
      success: function (res) {
        if (res.data.code == 0) {
          //console.log(res.data.data);
          that.setData({
            reputation: res.data.data
          });
        }
      }
    })
  }
})
